import React, { useState, useEffect, useImperativeHandle } from 'react';
import { Tabs, Card, Table, Row, Col, Select, Button, Typography } from 'antd';
import { connect } from 'dva';
import moment from 'moment';
import _ from 'lodash';
import { handlerApprovalStatusColor } from '@/utils/publicFunction';
import AuthorizedButton from '@/components/AuthorizedButton';
import PageEmpty from '@/components/PageEmpty';
import Btns from '@/components/Btns';
import {
  CONSTANT_TAB_KEY1, // 投资正式版
  CONSTANT_TAB_KEY2, // 调整版
  CONSTANT_TAB_KEY3, // 实际版
  CONSTANT_EMPTYMSG1, // emptyMsg
  CONSTANT_EMPTYMSG2, // 空数据
} from '../utils/constant';
import FormalTable from './FormalTable';
import * as request from '../utils/request';
import { getInvestUsingPOST } from '@/services/ReturnMoneyValueMgr';
const { Text } = Typography;
const { Option } = Select;

const Page = props => {
  const {
    dispatch,
    versionList,
    versionActive,
    match: { params },
  } = props;

  const [versionId, setVersionId] = useState('');
  const [data, setData] = useState([]);
  const [columns, setColumns] = useState([]);
  const [loading, setLoading] = useState(true);

  // 获取数据(表格 data 和 columns)
  const getData = async id => {
    if (!loading) setLoading(true);
    const res = await request.getFormalData(id);
    const { columns, data } = res;
    setData(data);
    setColumns(
      columns.map((tar, index) => {
        if (index === 0) return tar;
        return {
          ...tar,
          render: text => `${text}%`,
        };
      }),
    );
    setLoading(false);
    return;
  };

  // 整体刷新（获取版本列表=>获取表格数据）
  const refreshData = () => {
    const query = {
      projectId: params.project,
      versionType: CONSTANT_TAB_KEY1,
    };
    dispatch({
      type: 'PayBackModulus/getVersionsList',
      payload: query,
      callback: lastVersion => {
        if (lastVersion) {
          setVersionId(lastVersion.id);
          getData(lastVersion.id);
          return;
        }
        setLoading(false);
      },
    });
  };

  useEffect(() => {
    refreshData();
  }, [params.project]);

  // 版本切换
  const changeVersion = id => {
    const index = versionList.findIndex(tar => {
      return tar.id === id;
    });
    dispatch({
      type: 'PayBackModulus/save',
      payload: { versionActive: versionList[index] },
    });
    setVersionId(id);
    getData(id);
  };

  // 暴露方法给父组件
  useImperativeHandle(props.onRef, () => ({
    // changeVal 就是暴露给父组件的方法
    changeUpData: async callback => {
      setLoading(true);
      const res = await getInvestUsingPOST({ params: { projectId: params.project } });
      if (res && res.code === 1) refreshData();
      await setLoading(false);
      await callback();
    },
  }));

  return (
    <>
      {loading ? (
        <PageEmpty emptyTitle={CONSTANT_EMPTYMSG1} />
      ) : versionList.length === 0 ? (
        <PageEmpty emptyTitle={CONSTANT_EMPTYMSG2} />
      ) : (
        <>
          <Row type="flex" justify="space-between" align="middle" style={{ marginBottom: 10 }}>
            {versionActive && (
              <>
                <Col>
                  <Select
                    size="small"
                    // onChange={value => {
                    //   router.replace(
                    //     `/ValueManage/PriceManage/${params.level1}/${params.level2}/${params.project}/${params.stage}/${params.category}/${value}`,
                    //   );
                    // }}
                    onChange={changeVersion}
                    dropdownMatchSelectWidth={false}
                    className="version-select"
                    value={versionId}
                  >
                    {versionList.map(tar => (
                      <Option key={tar.id} value={tar.id}>
                        投资正式版{tar.versionNum}-{moment(tar.createTime).format('YYYYMMDD')}
                      </Option>
                    ))}
                  </Select>
                  <Text>
                    &ensp;同步于&nbsp;{moment(versionActive.syncTime).format('YYYY-MM-DD H:mm:ss')}
                  </Text>
                </Col>
              </>
            )}
            {/* <Col>
                  <Row gutter={[5, 0]} type="flex" justify="space-between" align="middle">
                    <Col>
                      <AuthorizedButton authority="business_payBackModulus_refresh">
                        <Button onClick={getInvestUsing}>刷新</Button>
                      </AuthorizedButton>
                    </Col>
                  </Row>
                </Col> */}
          </Row>
          <FormalTable dataSource={data} columns={columns} />
        </>
      )}
    </>
  );
};

export default connect(state => ({
  // versionList: state.PayBackModulus.versionList,
  // versionActive: state.PayBackModulus.versionActive,
}))(Page);
